package com.face.server.communication.mina.coder;

import com.face.server.common.domain.ByteArrayReceiverEx;
import com.face.server.common.utils.DataPacketUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * @author yangzhongming
 * @desc 人脸识别出纸机--mina 解码器
 * @date 2022/1/24
 */
public class ByteArrayDecoder extends CumulativeProtocolDecoder {
    @Override
    protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
        if (ioBuffer.remaining() > 2) {
            //标记当前position的快照标记mark，以便后继的reset操作能恢复position位置
            ioBuffer.mark();
            //获取命令头
            byte[] headers = new byte[3];
            ioBuffer.get(headers);
            //数据的长度
            int length = DataPacketUtil.bytesToInt(headers, 1, 2);

            if (ioBuffer.remaining() < length) {
                //如果消息内容不够，则重置恢复position位置到操作前,进入下一轮, 接收新数据，以拼凑成完整数据
                ioBuffer.reset();
                return false;
            } else {
                //消息内容足够
                byte[] contents = new byte[length];
                ioBuffer.get(contents);
                ByteArrayReceiverEx byteArrayReceiverEx = new ByteArrayReceiverEx();
                byteArrayReceiverEx.setOrder(headers[0]);
                byteArrayReceiverEx.setLength(length);
                byteArrayReceiverEx.setContent(contents);
                protocolDecoderOutput.write(byteArrayReceiverEx);

                if (ioBuffer.remaining() > 0) {
                    //如果读取一个完整包内容后还粘了包，就让父类再调用一次，进行下一次解析
                    return true;
                }
            }

        }
        //处理成功，让父类进行接收下个包
        return false;
    }
}
